#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
# @Time    : 2024/9/29 15:59 
# @Author  : SumKids 
# @Site    :  
# @File    : 05_window_show.py
# @Software: PyCharm
# @Description:

from PySide6.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QLineEdit, QVBoxLayout
import sys
from PySide6.QtCore import Signal  # 导入信号

'''
        自定义信号: 
            1. 主窗口向子窗口发送信号
            2. 子窗口向主窗口发送信号
'''


class MyWidget(QWidget):
    """
    DOC: 1.1 自定义信号：发送信号到子窗口，数据类型为 str
    """
    signal_send_to_sub_window = Signal(str)

    def __init__(self) -> None:
        super().__init__()
        self.setWindowTitle('自定义信号：主窗口')
        self.resize(400, 200)

        btn2 = QPushButton('触发自定义信号')
        btn2.clicked.connect(self.emit_custom_signal)

        self.lineEdit = QLineEdit('hhhh')

        # 创建标签显示子窗口状态
        self.statusLabel = QLabel()

        layout = QVBoxLayout()
        layout.addWidget(self.lineEdit)
        layout.addWidget(btn2)
        layout.addWidget(self.statusLabel)
        self.setLayout(layout)

        # 事件绑定
        self.bind()

    def bind(self):
        self.subWindow = SubWidget(parent=self)
        self.subWindow.show()
        """
            DOC: 1.2 绑定信号槽(触发信号后的处理函数)
        :rtype: object
        """
        self.signal_send_to_sub_window.connect(self.subWindow.handle_signal)

    def emit_custom_signal(self):
        """
            DOC: 1.3 触发信号
        :rtype: object
        """
        # 触发信号
        self.signal_send_to_sub_window.emit(self.lineEdit.text())

    def handle_signal(self, text):
        print(text)


class SubWidget(QWidget):
    """
        DOC：2.1 定义子窗口的信号
    """
    signal_sub_to_main = Signal(str)

    def __init__(self, parent=None):
        """
            DOC: 2.2 给子窗口初始化函数添加parent参数，用以接收主窗口对象，方便后续绑定子窗口信号的槽
                P.S. 注意要添加这一行：  self.parent = parent
        :rtype: object
        """
        super().__init__()
        self.parent = parent
        self.setWindowTitle('子窗口')
        self.resize(300, 50)
        label = QLabel('标签：')
        self.lineEdit = QLineEdit()
        btn = QPushButton('发送信号到主窗口')
        btn.clicked.connect(self.emit_signal_to_main)

        layout = QVBoxLayout()
        layout.addWidget(label)
        layout.addWidget(self.lineEdit)
        layout.addWidget(btn)
        self.setLayout(layout)
        self.bind()

    def bind(self):
        """
            DOC: 2.3 子窗口信号绑定槽为主窗口的函数
        :return:
        """
        self.signal_sub_to_main.connect(self.parent.handle_signal)

    def handle_signal(self, text):
        self.lineEdit.setText(text)

    def emit_signal_to_main(self):
        """
            DOC: 2.4 子窗口信号触发
        :return:
        """
        self.signal_sub_to_main.emit(self.lineEdit.text())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWidget()
    window.show()
    app.exec()
